package com.qf.service;
import com.qf.dao.StudentDao;
import com.qf.dao.utils.SqlSessionUtil;
import com.qf.entity.Student;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import java.util.List;

@Slf4j
public class StudentService {
    private SqlSession sqlSession = SqlSessionUtil.getSqlSession();
    private StudentDao mapper = sqlSession.getMapper(StudentDao.class);
    //查询学生总记录数
    private int count = mapper.getCount();
    @Test
    public String PickName(String type){
        //查询没有被点过的学生
        List<Student> noCalledList = mapper.findStudentByPrizeCount(0);
        List<Student> all = mapper.findAll();
        log.info(noCalledList.toString());
        if (type == "1"){
            //公平点名
            if (noCalledList.size() == 0){
                log.info("学生全被点过了~");
                mapper.updateAll();
                sqlSession.commit();
                sqlSession.close();
                return "学生全被点过了～请重启tomcat服务器";
            }
            Student student = RandomNum(noCalledList);
            student.setPrizeCount(student.getPrizeCount() + 1);
            mapper.update(student);
            sqlSession.commit();
            sqlSession.close();
            return student.getName();
        }else {
            //不公平点名  通过学生id查找学生对象
            //查询所有学生集合，随机抽取
            all = mapper.findAll();
            Student student = RandomNum(all);
            int prizeCount = student.getPrizeCount();
            prizeCount ++;
            student.setPrizeCount(prizeCount);
            mapper.update(student);
            sqlSession.commit();
            sqlSession.close();
            return student.getName();
        }
    }

    /**
     *  根据数据库长度产生随机数（即为学生id）,返回查询的学生对象
     * @param list
     * @return
     */
    public Student RandomNum(List<Student> list){
        int num = (int)(Math.random()* (list.size()));
        log.info("随机数为："+num);
        return list.get(num);
    }

    /**
     * 实现所有学生被点次数的接口
     * @return
     */
    public List<Student> getCount(){
        return mapper.findAll();
    }

}
